
#include "stdafx.h"
#include "config.h"

bool CONFIG::Load(const char * filename)
{
   std::ifstream input(filename);
   if (!input) {
      return false;
   }

   SECTION * cur = NULL;

   std::string stdline;
   while (std::getline(input, stdline)) {
      dsSTRING line = stdline.c_str();
      line.Trim();

      if (line.IsEmpty()) {
         continue;
      }

      if (line[0] == '[') {
         dsSTRING sectionName = line.SubStr(1, line.Length() - 2);
         SECTION_MAP::iterator iter = sections.FindInsert(sectionName);
         cur = &iter.value();
         cur->name = iter.key();
         
         continue;
      }

      int index = line.Find("=");
      if (index == -1) {
         // skip invalid lines
         continue;
      }

      // create default section
      if (cur == NULL) {
         cur = &sections.FindInsert("").value();
      }

      dsSTRING key   = line.SubStr(0, index).ToTrimmed();
      dsSTRING value = line.SubStr(index + 1, line.Length() - index - 1).ToTrimmed();

      cur->keys.FindInsert(key).value() = value;
   }

   return true;
}

const dsSTRING & CONFIG::GetValue(const dsSTRING & section, const dsSTRING & key, const dsSTRING & defVal /* = dsSTRING */) const
{
   SECTION_MAP::const_iterator sectionIter = sections.Find(section);
   if (sectionIter.IsDone()) {
      return defVal;
   }

   STRING_MAP::const_iterator valueIter = sectionIter->keys.Find(key);
   if (valueIter.IsDone()) {
      return defVal;
   }

   return *valueIter;
}

int CONFIG::GetInt(const dsSTRING & section, const dsSTRING & key, int defVal /* = 0 */) const
{
   dsSTRING strval = GetValue(section, key);
   if (strval.IsEmpty()) {
      return defVal;
   }

   return atoi(strval.CStr());
}

float CONFIG::GetFloat(const dsSTRING & section, const dsSTRING & key, float defVal /* = 0.f */) const
{
   dsSTRING strval = GetValue(section, key);
   if (strval.IsEmpty()) {
      return defVal;
   }

   return atof(strval.CStr());
}